<template>
  <el-dialog
    :title="isEdit ? '修改学科' : '新增学科'"
    :visible.sync="showDialog"
    width="450px"
    @close="onClose"
  >
    <el-form
      ref="fromRef"
      :model="addFormData"
      :rules="rules"
      label-width="80px"
    >
      <el-form-item label="所属学科" prop="subjectID">
        <el-select
          v-model="addFormData.subjectID"
          style="width: 200px"
          placeholder="请选择"
          size="small"
        >
          <el-option
            v-for="item in list"
            :key="item.id"
            :label="item.subjectName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="目录名称" prop="directoryName">
        <el-input
          v-model="addFormData.directoryName"
          size="small"
          placeholder="请输入目录名称"
        >
        </el-input>
      </el-form-item>
    </el-form>
    <el-row type="flex" justify="end">
      <el-col :span="5">
        <el-button @click="onClose">取消</el-button>
      </el-col>
      <el-col :span="5">
        <el-button type="primary" @click="btnOk">确认</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { list } from "@/api/hmmm/subjects";
import { add, detail, update } from "@/api/hmmm/directorys";
export default {
  data() {
    return {
      showDialog: false,
      addFormData: {
        subjectID: "",
        directoryName: null,
      },
      list: [],
      rules: {
        subjectID: [
          { required: true, message: "请选择所属学科", trigger: "change" },
        ],
        directoryName: [
          { required: true, message: "请输入目录名称", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getSubject();
  },
  computed: {
    isEdit() {
      return !!this.addFormData.id;
    },
  },
  methods: {
    async getSubject() {
      const res = await list();
      // console.log(items);
      this.list = res.data.items;
    },
    onClose() {
      (this.addFormData = {
        subjectID: "",
        directoryName: null,
      }),
        this.$refs.fromRef.resetFields();
      this.showDialog = false;
    },
    btnOk() {
      // 判断编辑和新增
      const fn = this.isEdit ? update : add;
      this.$refs.fromRef
        .validate()
        .then(() => {
          console.log(this.addFormData);
          // 调接口 目录添加
          return fn(this.addFormData);
        })
        .then(async () => {
          // 提醒用户
          this.$message.success(this.isEdit?"修改成功":"新增成功");
          // 告诉父组件
          await this.$emit("done");
          // 关闭弹框
          this.onClose();
        })
        .catch(() => {
          console.log("校验未通过");
        });
    },
    // 修改回显
    async update(row) {
      const res = await detail(row);
      console.log(res.data);
      this.addFormData = res.data;
      // 打开弹框
      this.showDialog = true;
    },
  },
};
</script>

<style scoped lang="less"></style>
